<template>
  <el-card>
    <div style="font-weight: bold; font-size: 25px">新增质检工单</div>
  </el-card>

  <el-card style="margin-top: 15px; margin-left: 15px; width: 80%">
    <!-- 表单区域 -->
    <el-form :model="ruleForm" label-width="120px" :rules="rules" ref="formRef">
      <div class="section-title">基础信息</div>

      <!-- 质检工单主题：独占一行（span=24） -->
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="质检工单主题" prop="quaworkname">
            <el-input
              v-model="ruleForm.quaworkname"
              placeholder="请输入质检工单主题"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 质检工单编号 + 来源工单：左右分布 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="质检工单编号">
            <el-input v-model="ruleForm.quaworkcode"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="来源工单">
            <el-select v-model="ruleForm.orderid" clearable>
              <el-option
                v-for="item in works"
                :key="item.id"
                :label="item.quaworkcode"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 生产物品 + 质检部门：左右分布 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="生产物品">
            <el-select v-model="ruleForm.itemid" clearable>
              <el-option
                v-for="item in boms"
                :key="item.id"
                :label="item.goodsname"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="质检部门" prop="department">
            <el-select v-model="department" placeholder="请选择部门" clearable>
              <el-option
                v-for="dept in departments"
                :key="dept.id"
                :label="dept.name"
                :value="dept.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 质检负责人 + 工序数量：左右分布 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="质检负责人" prop="accountid">
            <el-select
              v-model="ruleForm.accountid"
              placeholder="请选择质检负责人"
              clearable
            >
              <el-option
                v-for="item in users"
                :key="item.id"
                :label="item.realname"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="工序数量">
            <el-input v-model="ruleForm.processcount"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 备注：独占一行（span=24） -->
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="备注" prop="meeage">
            <el-input
              type="textarea"
              v-model="ruleForm.meeage"
              placeholder="请输入备注"
              :rows="4"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 操作按钮 -->
      <div class="footer-buttons">
        <el-button @click="close">关闭</el-button>
        <el-button type="primary" @click="submit">确定</el-button>
      </div>
    </el-form>
  </el-card>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import {
  ElForm,
  ElFormItem,
  ElInput,
  ElSelect,
  ElOption,
  ElButton,
  ElMessage,
} from "element-plus";
import myaxios from "@/Http/http";
import router from "@/router";

// 表单数据
const ruleForm = reactive({
  id: 0,
  quaworksubject: "质检主题",
  quaworkcode: "",
  quaworkname: "",
  orderid: null,
  completenum: 80,
  qualifiednum: 80,
  defectivenum: 0,
  itemid: null,
  status: 0,
  processid: 1000,
  processcount: null,
  reportingcount: 16,
  inspectioncount: 10,
  accountid: null,
  meeage: "",
  reportingtime: new Date().toISOString(),
  createtime: new Date().toISOString(),
  updatetime: new Date().toISOString(),
});
const department = ref([1]);
// 下拉选项数据
const departments = [{ id: "1", name: "质检部门" }];
const users = ref([
  {
    realname: "孙东博",
    id: 1,
  },
]);
const getUsers = () => {
    myaxios.get("api/Quality/GetUser").then((res) => {
      console.log("用户下拉数据：", res.data.result); // 确认数据是否返回
      users.value = res.data.result || [];
    });
};
const works = ref([
  {
    quaworkcode: "GD202511",
    id: 1,
  },
]);
const getWorks = () => {
  myaxios.get("api/Quality/GetWork").then((res) => {
    works.value = res.data.result || [];
  });
};

const boms = ref([
  {
    goodsname: "插座模块",
    id: 7,
  },
]);
const getBoms = () => {
  myaxios.get("api/Quality/GetBom").then((res) => {
    boms.value = res.data.result || [];
  });
};

// 表单校验规则
const rules = {
  quaworkname: [
    { required: true, message: "请输入质检工单主题", trigger: "blur" },
  ],
  accountid: [
    { required: true, message: "请选择质检负责人", trigger: "change" },
  ],
  meeage: [{ required: true, message: "请输入备注", trigger: "change" }],
};

const formRef = ref<InstanceType<typeof ElForm>>();

const submit = () => {
  formRef.value?.validate((valid) => {
    if (valid) {
      // 先检查ruleForm的内容
      console.log('原始ruleForm:', ruleForm);
      
      // 手动构建一个最简化的测试数据
      const testData = {
        realName: localStorage.getItem("realName"),
        qualityDtos: [
          ruleForm
        ]
      };
      
      console.log('测试数据:', JSON.stringify(testData, null, 2));

      myaxios
        .post("api/Quality/CreateQuality", testData)
        .then((res) => {
          console.log('成功响应:', res.data);
          if (res.data.code === 200) {
            ElMessage.success(res.data.message);
            router.push("/qualitylist");
          }
        })
        .catch((err) => {
          console.error('详细错误:', err.response?.data || err);
        });
    }
  });
};

// 关闭弹窗
const close = () => {
  router.push("/qualitylist");
};

// 页面加载时获取数据
onMounted(() => {
  getUsers();
  getWorks();
  getBoms();
});
</script>

<style scoped>
.section-title {
  font-size: 16px;
  font-weight: bold;
  margin: 20px 0 10px;
  color: #555;
}
.footer-buttons {
  text-align: right;
  margin-top: 30px;
}
.footer-buttons {
  display: flex;
  justify-content: center; /* 水平居中 */
  margin-top: 30px;
}
</style>
